﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.ComponentModel;

namespace SampleApp.Infrastructure
{
    // This provides support for strongly-typed property changed notification
    public static class ViewModelExtension
    {
        public static void OnPropertyChanged<T, TProperty>(this T observableBase, Expression<Func<T, TProperty>> expression) where T : IRaisePropertyChanged
        {
            observableBase.RaisePropertyChanged(observableBase.GetPropertyName(expression));
        }

        public static string GetPropertyName<T, TProperty>(this T owner, Expression<Func<T, TProperty>> expression)
        {
            var memberExpression = expression.Body as MemberExpression;
            
            if (memberExpression == null)
            {
                var unaryExpression = expression.Body as UnaryExpression;
                
                if (unaryExpression == null)
                {
                    throw new NotImplementedException();
                }

                memberExpression = unaryExpression.Operand as MemberExpression;
                if (memberExpression == null)
                {
                    throw new NotImplementedException();
                }
            }

            return memberExpression.Member.Name;
        }
    }
}
